﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QldtSdh.GUI.Common;
using QldtSdh.Utils;

namespace QldtSdh.GUI.DuLieu
{
    using BLL;
    using DAL;
    using DAL.Models;
    using QldtSdh.Utils;
    using QldtSdh.GUI.Utils;
    public partial class FormDeTai_Import : BaseDialog
    {
        public FormDeTai_Import()
        {
            InitializeComponent();
            gridDeTai.SetDataGridViewAsReadonly(rowHeadersVisible: false, columnHeadersVisible: true);
        }

        [System.ComponentModel.DataAnnotations.Schema.NotMapped]
        public class ImportedDeTai : DeTai
        {
            public static int CHUA_TON_TAI_LOAI_DE_TAI = 1;
            public static int TRUNG_TEN_DE_TAI = 2;

            /// <summary>
            /// Đã thực hiện thêm vào CSDL
            /// </summary>
            public bool DaImport { get; set; }

            public int ErrorCode { get; set; }
            public string TrangThai
            {
                get
                {
                    if (DaImport)
                        return "Đã nạp";
                    if (ErrorCode == 0)
                        return "";
                    string stError = (ErrorCode & CHUA_TON_TAI_LOAI_DE_TAI) == CHUA_TON_TAI_LOAI_DE_TAI ? "Chưa có Loại đề tài" : "";
                    if ((ErrorCode & TRUNG_TEN_DE_TAI) == TRUNG_TEN_DE_TAI)
                        if (string.IsNullOrEmpty(stError))
                            stError = "Trùng tên đề tài";
                        else
                            stError += ", Trùng tên đề tài";
                    return stError;
                }
            }
            public string TenLoaiDeTai { get; set; }
            public int STT { get; set; }
        }

        private List<ImportedDeTai> _ImportedDeTaiList = null;

        private void lnkSelectFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            dlg.Title = "Chọn tệp Excel...";
            dlg.Filter = "Tệp Excel (*.XLS)|*.xls";
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtExcelFileName.Text = dlg.FileName;
                NapDanhSachBangTinh();
            }
        }

        private void lnkGetSheetList_Click(object sender, EventArgs e)
        {
            NapDanhSachBangTinh();
        }

        private void NapDanhSachBangTinh()
        {
            ep.Clear();
            var filename = txtExcelFileName.Text;
            if (string.IsNullOrEmpty(filename))
            {
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Bạn chưa chọn tệp Excel");
                return;
            }
            try
            {
                var ei = new ExcelImporter(filename);
                var lstSheet = ei.GetSheetNameList();
                cbxSheet.Items.Clear();
                foreach (var sheet in lstSheet)
                    cbxSheet.Items.Add(sheet);
                if (lstSheet.Count > 0)
                    cbxSheet.SelectedIndex = 0;
            }
            catch (Exception exc)
            {
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Không thể nạp danh sách bảng tính\r\n" + exc.Message);
            }
        }

        private void btnReadSheetData_Click(object sender, EventArgs e)
        {
            #region var ei = new ExcelImporter() or return;
            ep.Clear();
            var filename = txtExcelFileName.Text;
            if (string.IsNullOrEmpty(filename))
            {
                ep.SetIconAlignment(lblExcelFilename, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblExcelFilename, "Bạn chưa chọn tệp Excel");
                return;
            }
            var ei = new ExcelImporter(filename);
            string sheetName = null;
            SheetName oSheetName = null;
            if (cbxSheet.SelectedItem != null)
                oSheetName = cbxSheet.SelectedItem as SheetName;
            if (oSheetName != null)
                sheetName = oSheetName.Name;
            if (string.IsNullOrEmpty(sheetName))
            {
                ep.SetIconAlignment(lblSheetname, ErrorIconAlignment.MiddleLeft);
                ep.SetError(lblSheetname, "Bạn chưa chọn bảng tính");
                return;
            }
            #endregion

            using (var db = DAL.Models.CEMS4UG_DHKHContext.GetContext())
            {
                var oBatDau = txtOBatDau.Text;
                var oKetThuc = txtOKetThuc.Text;
                var dt = ei.ReadData(sheetName, oBatDau, oKetThuc, false);
                var lstImportedDeTai = new List<ImportedDeTai>();
                foreach (DataRow drow in dt.Rows)
                {
                    // (STT, Tên đề tài, Người thực hiện, Năm bắt đầu, Năm kết thúc, Loại đề tài, Ghi chú)
                    var stSTT = Convert.ToString(drow[0]);
                    if (string.IsNullOrEmpty(stSTT))
                        break;
                    var stt = Convert.ToInt32(stSTT);

                    var tenDeTai = Convert.ToString(drow[1]);
                    var nguoiThucHien = Convert.ToString(drow[2]);
                    var namBatDau = Convert.ToString(drow[3]);
                    var namKetThuc = Convert.ToString(drow[4]);
                    var tenLoaiDeTai = Convert.ToString(drow[5]);
                    var ghiChu = Convert.ToString(drow[6]);
                    var importedDeTai = new ImportedDeTai()
                    {
                        STT = stt,
                        MaDeTai = System.Guid.NewGuid().ToString(),
                        TenDeTai = tenDeTai,
                        NguoiThucHien = nguoiThucHien,
                        NamThucHien = namBatDau,
                        NamBaoVe = namKetThuc,
                        TenLoaiDeTai = tenLoaiDeTai,
                        MaLoaiDeTai = "",
                        GhiChu = "",
                        ErrorCode = 0
                    };

                    var loaiDeTai = BizDeTai.FindLoaiDeTaiByTenLoaiDeTai(tenLoaiDeTai, db);
                    if (loaiDeTai == null)
                        importedDeTai.ErrorCode += ImportedDeTai.CHUA_TON_TAI_LOAI_DE_TAI;
                    else
                        importedDeTai.MaLoaiDeTai = loaiDeTai.MaLoaiDeTai;
                    if (BizDeTai.FindDeTaiByTenDeTai(tenDeTai, db) != null)
                        importedDeTai.ErrorCode += ImportedDeTai.TRUNG_TEN_DE_TAI;

                    lstImportedDeTai.Add(importedDeTai);
                }
                //bsHocPhanThi.DataSource = new SortableBindingList<HocPhanThi>(lstHocPhanThi);
                //gridHocPhanThi.AutoGenerateColumns = false;
                //gridHocPhanThi.DataSource = bsHocPhanThi;
                bsImportedDeTai.DataSource = new MySortableBindingList<ImportedDeTai>(lstImportedDeTai);
                gridDeTai.SetDataSource(bsImportedDeTai);
            }
        }

        private void UpdateGuiAsBusy(BackgroundWorker bw)
        {
            //btnCreateDeInRa.Text = "Huỷ ngang";
            //btnCreateDeInRa.Tag = bw;
            btnLuuDuLieu.Enabled = false;
            btnClose.Enabled = false;
            picBusy.Visible = true;
        }

        private void UpdateGuiAsFree()
        {
            //btnCreateDeInRa.Text = "Tạo đề thi";
            //btnCreateDeInRa.Tag = null;
            btnLuuDuLieu.Enabled = true;
            btnClose.Enabled = true;
            picBusy.Visible = false;
        }

        private DataGridViewCellStyle m_StrikeoutStyle = null;
        private DataGridViewCellStyle StrikeoutStyle
        {
            get
            {
                if (m_StrikeoutStyle == null)
                {
                    m_StrikeoutStyle = new DataGridViewCellStyle(gridDeTai.DefaultCellStyle);
                    m_StrikeoutStyle.Font = new Font(m_StrikeoutStyle.Font, FontStyle.Strikeout);
                    m_StrikeoutStyle.ForeColor = Color.Gray;
                }
                return m_StrikeoutStyle;
            }
        }

        private void gridDeTai_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < gridDeTai.Rows.Count; i++)
            {
                DataGridViewRow dgrow = gridDeTai.Rows[i];
                var deTai = dgrow.DataBoundItem as ImportedDeTai;
                if (deTai.ErrorCode == 0)
                {
                    for (int j = 1; j <= 6; j++)
                        dgrow.Cells[j].Style = null;
                }
                else
                {
                    for (int j = 1; j <= 6; j++)
                        dgrow.Cells[j].Style = StrikeoutStyle;
                }
            }
        }

        private void btnSaveImportedData_Click(object sender, EventArgs e)
        {
            ep.Clear();
            MySortableBindingList<ImportedDeTai> lstDeTai = null;
            if (bsImportedDeTai.DataSource != null)
                lstDeTai = bsImportedDeTai.DataSource as MySortableBindingList<ImportedDeTai>;
            if (lstDeTai == null)
            {
                ep.SetError(btnLuuDuLieu, "Chưa có dữ liệu");
                return;
            }

            using (var db = CEMS4UG_DHKHContext.GetContext())
            {
                var nThanhCong = 0;
                try
                {
                    foreach (var x in lstDeTai)
                    {
                        if (x.DaImport)
                            continue;
                        if (x.ErrorCode > 0)
                            continue;
                        var deTai = new DeTai()
                        {
                            MaDeTai = x.MaDeTai,
                            TenDeTai = x.TenDeTai,
                            NguoiThucHien = x.NguoiThucHien,
                            NamThucHien = x.NamThucHien,
                            NamBaoVe = x.NamBaoVe,
                            MaLoaiDeTai = x.MaLoaiDeTai,
                            GhiChu = x.GhiChu
                        };
                        db.DeTaiDbSet.Add(deTai);
                        nThanhCong++;
                        BizNhatKyHoatDong.LogAndCommitInsert2(deTai, deTai.MaDeTai, LOAIDOITUONG.DE_TAI, db);
                        x.DaImport = true;
                    }
                    DialogUtils.ShowMessage(string.Format("Đã nạp {0} đề tài vào hệ thống", nThanhCong));
                }
                catch (Exception exc)
                {
                    DialogUtils.ShowErrorWithDefaultTitle("Xuất hiện lỗi trong quá trình nạp đề tài vào hệ thống.\r\n" + exc.Message);
                }
                bsImportedDeTai.ResetBindings(false);
            }
        }
    }
}
